<script setup lang="ts">
import { ref, onMounted, watch } from 'vue'
import { i18n } from 'boot/i18n'
import service from 'src/api/service'
import { date } from 'quasar'

const tc = i18n.global.tc

// 当天日期
const today = new Date()

// 选中的日期（默认为今天）
const selectedDate = ref(date.formatDate(today, 'YYYY/MM/DD'))

// 时间戳处理函数
const getStartOfDay = (dateStr = selectedDate.value) => {
  const start = new Date(dateStr)
  start.setHours(0, 0, 0, 0)
  return Math.floor(start.getTime() / 1000)
}

const getEndOfDay = (dateStr = selectedDate.value) => {
  const end = new Date(dateStr)
  end.setHours(23, 59, 59, 999)
  return Math.floor(end.getTime() / 1000)
}

// 计算当前时间戳
const currentTime = Math.floor(Date.now() / 1000)

// 全局统计数据（全时间范围）
const globalStats = ref({
  totalBookings: 0,
  completedBookings: 0,
  canceledBookings: 0,
  upcomingBookings: 0, // 添加全局即将开始预定数量
  ongoingBookings: 0, // 添加全局进行中预定数量
  noShowRate: 0 // 百分比
})

// 单日统计数据
const dailyStats = ref({
  todayBookings: 0,
  upcomingBookings: 0, // 单日即将开始
  ongoingBookings: 0, // 单日进行中
  completedBookings: 0, // 单日已完成
  canceledBookings: 0, // 单日已取消
  resourceUtilization: 0 // 单日资源利用率
})

// 资源使用情况数据（单日）
const resourceUsage = ref([
  { type: '50方', total: 0, used: 0, available: 0 },
  { type: '100方', total: 0, used: 0, available: 0 },
  { type: '300方', total: 0, used: 0, available: 0 },
  { type: '500方', total: 0, used: 0, available: 0 },
  { type: '1000方', total: 0, used: 0, available: 0 }
])

// 最近预定数据类型定义
interface RecentBooking {
  id: string;
  user: string;
  topic: string;
  startTime: string;
  endTime: string;
  roomType: string;
  status: string;
  participants?: number;
  creationTime?: string; // 添加预定时间字段
}

// 最近预定数据
const recentBookings = ref<RecentBooking[]>([])

// 获取会议室配置
const fetchMeetingRoomConfig = async () => {
  try {
    const { data } = await service.txMeeting.getMeetingRoomConfig()
    if (data && data.room_info) {
      const roomInfo = data.room_info

      resourceUsage.value = [
        { type: '50方', total: roomInfo.type_50_num, used: 0, available: roomInfo.type_50_num },
        { type: '100方', total: roomInfo.type_100_num, used: 0, available: roomInfo.type_100_num },
        { type: '300方', total: roomInfo.type_300_num, used: 0, available: roomInfo.type_300_num },
        { type: '500方', total: roomInfo.type_500_num, used: 0, available: roomInfo.type_500_num },
        { type: '1000方', total: roomInfo.type_1000_num, used: 0, available: roomInfo.type_1000_num }
      ]
    }
  } catch (error) {
    console.error('获取会议室配置失败:', error)
  }
}

// 获取可用会议室资源（单日）
const fetchDailyUsableRooms = async () => {
  try {
    // 使用选中日期的开始和结束时间
    const startTime = getStartOfDay()
    const endTime = getEndOfDay()

    const { data } = await service.txMeeting.getUsableMeetingRooms({
      start_time: startTime,
      end_time: endTime
    })

    if (data && data.data) {
      // 更新资源使用情况
      data.data.forEach(item => {
        const roomType = item.room_type
        const index = resourceUsage.value.findIndex(r => r.type === `${roomType}方`)
        if (index !== -1) {
          resourceUsage.value[index].used = item.reserved
          resourceUsage.value[index].available = item.total - item.reserved
        }
      })

      // 计算单日资源利用率
      let totalRooms = 0
      let totalUsed = 0

      resourceUsage.value.forEach(room => {
        totalRooms += room.total
        totalUsed += room.used
      })

      dailyStats.value.resourceUtilization = totalRooms > 0
        ? Math.round((totalUsed / totalRooms) * 100)
        : 0
    }
  } catch (error) {
    console.error('获取单日可用会议室失败:', error)
  }
}

// 获取全局预定统计数据（全时间）
const fetchGlobalReservations = async () => {
  try {
    // 获取所有预定（不限日期）
    const { data: allData } = await service.txMeeting.listReservations({
      'as-admin': true,
      page_size: 1000
    })

    if (allData && allData.results) {
      // 计算已取消的预定数
      const canceledBookings = allData.results.filter(r => r.status === 'cancelled').length
      globalStats.value.canceledBookings = canceledBookings

      // 计算爽约率（假设爽约率为取消预定占总预定的百分比）
      globalStats.value.noShowRate = globalStats.value.totalBookings > 0
        ? parseFloat(((canceledBookings / globalStats.value.totalBookings) * 100).toFixed(1))
        : 0

      // 计算已完成的预定
      const completedBookings = allData.results.filter(r =>
        r.end_time < currentTime && r.status === 'reserved'
      )
      globalStats.value.completedBookings = completedBookings.length

      // 计算全局即将开始的预定
      const upcomingBookings = allData.results.filter(r =>
        r.start_time > currentTime && r.status === 'reserved'
      )
      globalStats.value.upcomingBookings = upcomingBookings.length

      // 计算全局进行中的预定
      const ongoingBookings = allData.results.filter(r =>
        r.start_time <= currentTime && r.end_time >= currentTime && r.status === 'reserved'
      )
      globalStats.value.ongoingBookings = ongoingBookings.length

      // 计算总预定数（已完成+进行中+即将开始+已取消）
      globalStats.value.totalBookings =
        globalStats.value.completedBookings +
        globalStats.value.ongoingBookings +
        globalStats.value.upcomingBookings +
        globalStats.value.canceledBookings

      // 获取最近的预定（未来和最近完成的）
      const recentReservations = [...allData.results]
        .sort((a, b) => {
          // 先尝试按照creation_time降序排列
          if (a.creation_time && b.creation_time) {
            return new Date(b.creation_time).getTime() - new Date(a.creation_time).getTime()
          }
          // 如果creation_time不可用，则按照接近当前时间的方式排序（保留原来的备选排序）
          return Math.abs(a.start_time - currentTime) - Math.abs(b.start_time - currentTime)
        })
        .slice(0, 4)
        .map(reservation => ({
          id: reservation.id,
          user: reservation.user.full_name || reservation.user.username,
          topic: reservation.subject,
          startTime: new Date(reservation.start_time * 1000).toISOString(),
          endTime: new Date(reservation.end_time * 1000).toISOString(),
          roomType: `${reservation.room_type}方`,
          status: getBookingStatus(reservation),
          participants: 0, // 由于API未返回此字段，暂时设为0
          creationTime: reservation.creation_time ? new Date(new Date(reservation.creation_time).getTime()).toISOString() : undefined
        }))

      recentBookings.value = recentReservations
    }
  } catch (error) {
    console.error('获取全局预定列表失败:', error)
  }
}

// 获取单日预定统计数据
const fetchDailyReservations = async () => {
  try {
    const dailyStart = getStartOfDay()
    const dailyEnd = getEndOfDay()

    // 获取预定（不使用API参数过滤，而是在代码中过滤）
    const { data: allData } = await service.txMeeting.listReservations({
      'as-admin': true,
      page_size: 1000
    })

    if (allData && allData.results) {
      // 过滤单日预定数据
      const dailyData = allData.results.filter(r =>
        r.start_time >= dailyStart && r.start_time <= dailyEnd
      )

      // 单日已取消
      dailyStats.value.canceledBookings = dailyData.filter(r =>
        r.status === 'cancelled'
      ).length

      // 单日即将开始
      dailyStats.value.upcomingBookings = dailyData.filter(r =>
        r.start_time > currentTime && r.status === 'reserved'
      ).length

      // 单日进行中
      dailyStats.value.ongoingBookings = dailyData.filter(r =>
        r.start_time <= currentTime && r.end_time >= currentTime && r.status === 'reserved'
      ).length

      // 单日已完成
      dailyStats.value.completedBookings = dailyData.filter(r =>
        r.end_time < currentTime && r.status === 'reserved'
      ).length

      // 计算单日预定总数（已完成+进行中+即将开始+已取消）
      dailyStats.value.todayBookings =
        dailyStats.value.completedBookings +
        dailyStats.value.ongoingBookings +
        dailyStats.value.upcomingBookings +
        dailyStats.value.canceledBookings
    }
  } catch (error) {
    console.error('获取单日预定列表失败:', error)
  }
}

// 更新选中日期的数据
const updateDailyData = async () => {
  await fetchDailyReservations()
  await fetchDailyUsableRooms()
}

// 监听日期变化，更新数据
watch(selectedDate, () => {
  updateDailyData()
})

// 定义预定数据接口
interface Reservation {
  status: string;
  start_time: number;
  end_time: number;
  [key: string]: unknown; // 允许其他属性
}

// 获取会议状态
const getBookingStatus = (reservation: Reservation): string => {
  const now = currentTime

  if (reservation.status === 'cancelled') {
    return 'canceled'
  } else if (now < reservation.start_time) {
    return 'upcoming'
  } else if (now > reservation.end_time) {
    return 'completed'
  } else {
    return 'ongoing'
  }
}

// 获取状态样式
const getStatusColor = (status: string) => {
  switch (status) {
    case 'upcoming':
      return 'primary'
    case 'ongoing':
      return 'warning'
    case 'completed':
      return 'positive'
    case 'canceled':
      return 'grey'
    default:
      return 'grey'
  }
}

// 获取状态文本
const getStatusText = (status: string) => {
  switch (status) {
    case 'upcoming':
      return tc('待开始')
    case 'ongoing':
      return tc('进行中')
    case 'completed':
      return tc('已完成')
    case 'canceled':
      return tc('已取消')
    default:
      return status
  }
}

// 格式化日期时间
const formatDateTime = (dateStr: string) => {
  const date = new Date(dateStr)
  return date.toLocaleString()
}

// 在组件挂载时获取数据
onMounted(async () => {
  await fetchMeetingRoomConfig()
  await fetchGlobalReservations()
  await fetchDailyReservations()
  await fetchDailyUsableRooms()
})
</script>

<template>
  <q-scroll-area style="height: calc(100vh - 50px)">
    <div class="q-pa-md">
      <h5 class="q-mt-none q-mb-md">{{ tc('仪表盘') }}</h5>

      <!-- 全局统计区域（全时间范围） -->
      <div class="q-mb-lg">
        <div class="row q-col-gutter-md q-mb-md">
          <!-- 全局统计标题背景 -->
          <div class="col-12">
            <q-banner class="bg-primary text-white">
              <div class="text-h6">{{ tc('全局统计') }}</div>
            </q-banner>
          </div>
        </div>

        <div class="row q-col-gutter-md">
          <!-- 总预定数 -->
          <div class="col-12 col-md-3 col-lg-2">
            <q-card class="dashboard-card">
              <q-card-section>
                <div class="text-subtitle2">{{ tc('预定总数') }}</div>
                <div class="text-h4 text-primary q-mt-sm">{{ globalStats.totalBookings }}</div>
              </q-card-section>
            </q-card>
          </div>

          <!-- 已完成预定 -->
          <div class="col-12 col-md-3 col-lg-2">
            <q-card class="dashboard-card">
              <q-card-section>
                <div class="text-subtitle2">{{ tc('已完成') }}</div>
                <div class="text-h4 text-positive q-mt-sm">{{ globalStats.completedBookings }}</div>
              </q-card-section>
            </q-card>
          </div>

          <!-- 进行中预定 -->
          <div class="col-12 col-md-3 col-lg-2">
            <q-card class="dashboard-card">
              <q-card-section>
                <div class="text-subtitle2">{{ tc('进行中') }}</div>
                <div class="text-h4 text-warning q-mt-sm">{{ globalStats.ongoingBookings }}</div>
              </q-card-section>
            </q-card>
          </div>

          <!-- 即将开始预定 -->
          <div class="col-12 col-md-3 col-lg-2">
            <q-card class="dashboard-card">
              <q-card-section>
                <div class="text-subtitle2">{{ tc('待开始') }}</div>
                <div class="text-h4 text-primary q-mt-sm">{{ globalStats.upcomingBookings }}</div>
              </q-card-section>
            </q-card>
          </div>

          <!-- 已取消预定 -->
          <div class="col-12 col-md-3 col-lg-2">
            <q-card class="dashboard-card">
              <q-card-section>
                <div class="text-subtitle2">{{ tc('已取消') }}</div>
                <div class="text-h4 text-grey q-mt-sm">{{ globalStats.canceledBookings }}</div>
              </q-card-section>
            </q-card>
          </div>
        </div>
      </div>

      <!-- 单日统计区域 -->
      <div class="q-mb-lg">

        <div class="row q-col-gutter-md q-mb-md">
          <!-- 单日预定统计标题背景 -->
          <div class="col-12">
            <q-banner class="bg-primary text-white">
              <div class="row items-center">
                <div class="text-h6">{{ tc('单日统计') }}</div>
                <q-input class="col-auto q-ml-md" v-model="selectedDate" outlined dense bg-color="white" mask="date"
                  :input-style="{ color: 'black' }" :rules="['date']">
                  <template v-slot:append>
                    <q-icon name="event" class="cursor-pointer">
                      <q-popup-proxy cover transition-show="scale" transition-hide="scale">
                        <q-date v-model="selectedDate" mask="YYYY/MM/DD">
                          <div class="row items-center justify-end">
                            <q-btn v-close-popup label="确定" color="primary" flat />
                          </div>
                        </q-date>
                      </q-popup-proxy>
                    </q-icon>
                  </template>
                </q-input>
              </div>
            </q-banner>
          </div>
        </div>

        <div class="row q-col-gutter-md q-mb-md">
          <!-- 单日预定总数 -->
          <div class="col-12 col-md-3 col-lg-2">
            <q-card class="dashboard-card">
              <q-card-section>
                <div class="text-subtitle2">{{ tc('预定总数') }}</div>
                <div class="text-h4 text-primary q-mt-sm">{{ dailyStats.todayBookings }}</div>
              </q-card-section>
            </q-card>
          </div>

          <!-- 单日已完成 -->
          <div class="col-12 col-md-3 col-lg-2">
            <q-card class="dashboard-card">
              <q-card-section>
                <div class="text-subtitle2">{{ tc('已完成') }}</div>
                <div class="text-h4 text-positive q-mt-sm">{{ dailyStats.completedBookings }}</div>
              </q-card-section>
            </q-card>
          </div>

          <!-- 单日进行中 -->
          <div class="col-12 col-md-3 col-lg-2">
            <q-card class="dashboard-card">
              <q-card-section>
                <div class="text-subtitle2">{{ tc('进行中') }}</div>
                <div class="text-h4 text-warning q-mt-sm">{{ dailyStats.ongoingBookings }}</div>
              </q-card-section>
            </q-card>
          </div>

          <!-- 单日即将开始 -->
          <div class="col-12 col-md-3 col-lg-2">
            <q-card class="dashboard-card">
              <q-card-section>
                <div class="text-subtitle2">{{ tc('待开始') }}</div>
                <div class="text-h4 text-primary q-mt-sm">{{ dailyStats.upcomingBookings }}</div>
              </q-card-section>
            </q-card>
          </div>

          <!-- 单日已取消 -->
          <div class="col-12 col-md-3 col-lg-2">
            <q-card class="dashboard-card">
              <q-card-section>
                <div class="text-subtitle2">{{ tc('已取消') }}</div>
                <div class="text-h4 text-grey q-mt-sm">{{ dailyStats.canceledBookings }}</div>
              </q-card-section>
            </q-card>
          </div>
        </div>

        <div class="row q-col-gutter-md q-mb-md">
          <!-- 单日资源使用情况 -->
          <div class="col-12">
            <q-card>
              <q-card-section>
                <div class="text-h6">{{ tc('资源使用情况') }}</div>
                <div class="row q-col-gutter-md q-mt-sm">
                  <div v-for="resource in resourceUsage" :key="resource.type" class="col-12 col-sm-6 col-md-4 col-lg-2">
                    <q-card flat bordered>
                      <q-card-section>
                        <div class="text-subtitle2 row justify-between items-center">
                          <span>{{ resource.type }}</span>
                          <q-badge v-if="resource.total > 0"
                            :color="resource.used / resource.total > 0.7 ? 'negative' : resource.used / resource.total > 0.3 ? 'warning' : 'positive'"
                            class="q-ml-sm">
                            {{ tc('使用率') }}: {{ Math.round((resource.used / resource.total) * 100) || 0 }}%
                          </q-badge>
                          <q-badge v-else color="grey" class="q-ml-sm">
                            {{ tc('使用率') }}: 0%
                          </q-badge>
                        </div>
                        <div class="row items-center q-mt-xs">
                          <div class="col-auto text-caption text-grey">{{ tc('已用') }}: {{ resource.used }}</div>
                          <div class="col">
                            <q-linear-progress :value="resource.total > 0 ? resource.used / resource.total : 0"
                              color="primary" class="q-mx-sm" />
                          </div>
                          <div class="col-auto text-caption text-grey">{{ tc('总量') }}: {{ resource.total }}</div>
                        </div>
                      </q-card-section>
                    </q-card>
                  </div>
                </div>
              </q-card-section>
            </q-card>
          </div>
        </div>
      </div>

      <!-- 实时统计区域 -->
      <div>
        <div class="row q-col-gutter-md q-mb-md">
          <!-- 实时统计标题背景 -->
          <div class="col-12">
            <q-banner class="bg-primary text-white">
              <div class="text-h6">{{ tc('实时统计') }}</div>
            </q-banner>
          </div>
        </div>

        <div class="row q-col-gutter-md">
          <!-- 最近预定 -->
          <div class="col-12">
            <q-card>
              <q-card-section>
                <div class="text-h6">{{ tc('最近预定') }}</div>
                <q-list separator dense>
                  <q-item v-for="booking in recentBookings" :key="booking.id" clickable v-ripple dense>
                    <q-item-section avatar>
                      <q-chip :color="getStatusColor(booking.status)" text-color="white" dense square>
                        {{ getStatusText(booking.status) }}
                      </q-chip>
                    </q-item-section>

                    <q-item-section>
                      <q-item-label class="text-weight-medium">{{ booking.topic }}</q-item-label>
                      <div class="row full-width q-mt-xs booking-info-row items-center">
                        <div class="col-auto">
                          <q-item-label caption class="booking-caption-item">
                            <div class="row items-center">
                              <q-icon name="person" size="xs" class="q-mr-xs" />
                              {{ tc('预定人') }}: {{ booking.user }}
                            </div>
                          </q-item-label>

                        </div>
                        <div class="col-auto q-ml-md">
                          <q-item-label caption class="booking-caption-item">
                            <div class="row items-center">
                              <q-icon name="event" size="xs" class="q-mr-xs" />
                              {{ tc('创建时间') }}: {{ booking.creationTime ? formatDateTime(booking.creationTime) :
                                tc('未知') }}
                            </div>
                          </q-item-label>
                        </div>
                      </div>
                      <div class="row booking-info-row items-center">
                        <div class="col-auto">
                          <q-item-label caption class="booking-caption-item">
                            <div class="row items-center">
                              <q-icon name="schedule" size="xs" class="q-mr-xs" />
                              {{ formatDateTime(booking.startTime) }} - {{ formatDateTime(booking.endTime) }}
                            </div>
                          </q-item-label>
                        </div>
                        <div class="col-auto q-ml-md">
                          <q-item-label caption class="booking-caption-item">
                            <div class="row items-center">
                              <q-icon name="meeting_room" size="xs" class="q-mr-xs" />
                              {{ booking.roomType }}
                              <q-icon name="groups" size="xs" class="q-ml-md q-mr-xs" />
                              {{ tc('参会人数') }}: {{ booking.participants }}
                            </div>
                          </q-item-label>
                        </div>
                      </div>
                    </q-item-section>
                  </q-item>
                </q-list>
              </q-card-section>
            </q-card>
          </div>
        </div>
      </div>
    </div>
  </q-scroll-area>
</template>

<style lang="scss" scoped>
.dashboard-card {
  transition: all 0.3s;

  &:hover {
    transform: translateY(-5px);
    box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
  }
}

.booking-info-row {
  margin-top: 2px;
}

.booking-caption-item {
  line-height: 1.2;
}

@media (max-width: 767px) {
  .booking-info-row {
    flex-wrap: wrap !important;

    .col-auto {
      margin-left: 0 !important;
      margin-bottom: 2px;
      width: 100%;
    }

    .q-ml-md {
      margin-left: 0 !important;
      margin-top: 2px;
    }
  }
}
</style>
